﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EC.Merchant.Controllers
{
    using EC.Application.Interface;

    using EC.Entity;
    using EC.Entity.Enum;
    using EC.Entity.Query;
    using EC.Entity.Request.Business;
    using EC.Entity.Request.User;
    using EC.Entity.Tables;
    using EC.Util;
    using Google_Authenticator_netcore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using System.IO;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 商户控制器
    /// </summary>
    public class BusinessController : BaseController
    {
        #region 注入
        /// <summary>
        /// 商户数据接口
        /// </summary>
        private readonly BusinessService _businessService;

        /// <summary>
        /// 余额接口日志
        /// </summary>
        private readonly BalanceLogService _balanceLogService;

        /// <summary>
        /// 存款订单接口
        /// </summary>
        private readonly DepositOrderService _depositOrderService;

        /// <summary>
        /// 付款订单接口
        /// </summary>
        private readonly PaymentRecordService _paymentRecordService;

        /// <summary>
        /// 结算接口
        /// </summary>
        private readonly SettleService _settleService;

        /// <summary>
        /// 商户接口
        /// </summary>
        private readonly MerchantService _merchantService;

        /// <summary>
        /// 权限接口
        /// </summary>
        private readonly AuthService _authService;

        /// <summary>
        /// 
        /// </summary>
        private IHostingEnvironment _hostingEnv;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context"></param>
        public BusinessController(BusinessService businessService, BalanceLogService balanceLogService, DepositOrderService depositOrderService, PaymentRecordService paymentRecordService, SettleService settleService, MerchantService merchantService, AuthService authService, IHostingEnvironment hostingEnv, LoginService loginService) : base(loginService)
        {
            _businessService = businessService;
            _balanceLogService = balanceLogService;
            _depositOrderService = depositOrderService;
            _paymentRecordService = paymentRecordService;
            _settleService = settleService;
            _merchantService = merchantService;
            _authService = authService;
            _hostingEnv = hostingEnv;
        }
        #endregion

        #region 余额管理
        /// <summary>
        /// 余额管理
        /// </summary>
        /// <returns></returns>
        public IActionResult Balance()
        {
            ViewBag.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            ViewBag.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            ViewBag.BalanceLogSource = EnumUtil.ToDictionary(typeof(BalanceLogSource));
            //获取商户
            var merchant = _businessService.GetMerchant(MerchantId);
            if (merchant != null)
            {
                ViewBag.DepositBalance = merchant.DepositBalance;
                ViewBag.PaymentProxyFrozenBalance = merchant.PaymentProxyFrozenBalance;
                ViewBag.PaymentBalance = merchant.PaymentBalance;
                ViewBag.DepositProxyFrozenBalance = merchant.DepositProxyFrozenBalance;
            }
            else
            {
                ViewBag.DepositBalance = "0.00";
                ViewBag.PaymentProxyFrozenBalance = "0.00";
                ViewBag.PaymentBalance = "0.00";
                ViewBag.DepositProxyFrozenBalance = "0.00";
            }

            if (UserPermissions != null && UserPermissions.Any(c => c.Contains("MerchantWithdrawal0001")))
            {
                ViewBag.MerchantWithdrawal = "MerchantWithdrawal0001";
            }
            else
            {
                ViewBag.MerchantWithdrawal = "";
            }

            if (UserPermissions != null && UserPermissions.Any(c => c.Contains("MerchantRechargel0001")))
            {
                ViewBag.MerchantRecharge = "MerchantRechargel0001";
            }
            else
            {
                ViewBag.MerchantRecharge = "";
            }
            return View();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<?></returns>
        public IActionResult BalanceQuery(BalanceLogQuery query)
        {
            query.MerchantIds = new List<int>() { MerchantId };
            var list = _balanceLogService.GetPager(query);

            return PartialView("_BalanceQuery", list);
        }

        public JsonResult BalanceExport(BalanceLogQuery query)
        {
            query.CurrentPageIndex = 1;
            query.PageSize = 500;
            query.MerchantIds = new List<int>() { MerchantId };

            var list = _balanceLogService.GetBalanceExportPager(query);
            list.StatusCode = $"{query.StartTime}-{query.EndTime}";
            return Json(list);
        }

        /// <summary>
        /// 提现
        /// </summary>
        /// <returns></returns>
        public IActionResult Withdrawal()
        {
            var merchantResponse = _businessService.GetMerchant(MerchantId);

            return View(merchantResponse);
        }

        /// <summary>
        /// 提现
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveWithdrawal(SaveWithdrawalRequest request)
        {
            request.UserId = UserId;
            request.MerchantId = MerchantId;

            var response = _businessService.SaveWithdrawal(request);

            return Json(response);
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <returns></returns>
        public IActionResult Recharge()
        {
            var merchantResponse = _businessService.GetMerchant(MerchantId);

            return View(merchantResponse);
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveRecharge(SaveRechargeRequest request)
        {
            request.UserId = UserId;
            request.MerchantId = MerchantId;

            var response = _businessService.SaveRecharge(request);

            return Json(response);
        }
        #endregion

        #region 结算订单
        /// <summary>
        /// 结算管理
        /// </summary>
        /// <returns></returns>
        public IActionResult Settle()
        {
            ViewBag.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
            ViewBag.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            return View();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<?></returns>
        public JsonResult SettleQuery(SettleQuery query)
        {
            query.MerchantIds = new List<int>() { MerchantId };

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }

            var list = _settleService.GetPager(query);

            return Json(list);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public JsonResult SettleExport(SettleQuery query)
        {
            query.Page = 1;
            query.Rows = 500;
            query.MerchantIds = new List<int>() { MerchantId };

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }

            var list = _settleService.GetPager(query);

            list.StatusCode = $"{query.StartTime}-{query.EndTime}";

            return Json(list);
        }
        #endregion

        #region 收款订单
        /// <summary>
        /// 收款订单
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult DepositOrder()
        {
            ViewBag.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
            ViewBag.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private bool IsDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 收款记录
        /// </summary>
        /// <returns>PagedList<?></returns>
        public JsonResult DepositOrderQuery(DepositOrderQuery query)
        {
            query.UserPermission = UserPermissions;
            query.MerchantIds = new List<int>() { MerchantId };

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }

            var list = _depositOrderService.Pager(query);

            return Json(list);
        }

        /// <summary>
        /// 收款记录导出
        /// </summary>
        /// <returns>PagedList<?></returns>
        public JsonResult DepositOrderExport(DepositOrderQuery query)
        {
            query.UserPermission = UserPermissions;
            query.Page = 1;
            query.Rows = 500;
            query.MerchantIds = new List<int>() { MerchantId };

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }

            var list = _depositOrderService.Pager(query);
            list.StatusCode = $"{query.StartTime}-{query.EndTime}";
            return Json(list);
        }
        #endregion

        #region 下发订单
        /// <summary>
        /// 下发订单
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult PaymentRecord()
        {
            ViewBag.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
            ViewBag.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            return View();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<?></returns>
        public IActionResult PaymentRecordQuery(PaymentRecordQuery query)
        {
            query.UserPermission = UserPermissions;
            query.MerchantIds = new List<int>() { MerchantId };
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }

            var list = _paymentRecordService.GetPager(query);

            return Json(list);
        }

        /// <summary>
        /// 汇入EXCEL
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadFiles()
        {
            var response = new JResult()
            {
                Success = false
            };

            IFormFile file = Request.Form.Files[0];

            string folderName = "Upload";
            string webRootPath = _hostingEnv.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }

            try
            {


                if (file.Length > 0)
                {
                    Guid newName = Guid.NewGuid();
                    string sFileExtension = Path.GetExtension(file.FileName).ToLower();
                    ISheet sheet;
                    string fullPath = Path.Combine(newPath, newName + file.FileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                        stream.Position = 0;
                        if (sFileExtension == ".xls")
                        {
                            HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats  
                            sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook  
                        }
                        else
                        {
                            XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format  
                            sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook   
                        }

                        var merchant = _merchantService.Get(MerchantId);

                        #region 
                        var paymentRecords = new List<PaymentRecord>();

                        for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                        {
                            var model = new PaymentRecord();
                            //获取当前行
                            var row = sheet.GetRow(i);
                            if (row == null) continue;
                            if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
                            int j = row.FirstCellNum;

                            var orderNo = row.Cells[0].ToString().Trim();
                            var bankName = row.Cells[1].ToString().Trim();
                            var cardName = row.Cells[2].ToString().Trim();
                            var cardNumber = row.Cells[3].ToString().Trim();
                            var amount = row.Cells[4].ToString().Trim();
                            var fee = new decimal(0);

                            //订单号
                            var orderNoReg = new Regex(@"^[A-Za-z0-9]+$");
                            if (!orderNoReg.IsMatch(orderNo))
                            {
                                throw new Exception("订单号只能为字母、数字.");
                            }
                            //银行名称
                            if (string.IsNullOrEmpty(bankName))
                            {
                                throw new Exception("银行名称不能为空.");
                            }
                            //姓名
                            if (string.IsNullOrEmpty(cardName))
                            {
                                throw new Exception("姓名不能为空.");
                            }
                            //卡号
                            if (string.IsNullOrEmpty(cardNumber))
                            {
                                throw new Exception("卡号不能为空.");
                            }
                            // 检查提款金额货币格式有误的货币格式是否正确
                            decimal withdrawalAmount;
                            try
                            {
                                withdrawalAmount = Convert.ToDecimal(amount);
                            }
                            catch (Exception)
                            {
                                throw new Exception("代付金额货币格式有误");
                            }

                            //手续费计算
                            if (merchant.PaymentSingle > 0)
                            {
                                fee = merchant.PaymentSingle;
                            }
                            else
                            {
                                fee = withdrawalAmount * merchant.PaymentRate;
                            }

                            var total = withdrawalAmount + fee;

                            model.MerchantId = MerchantId;
                            model.MerchantOrderNo = orderNo;
                            model.WithdrawalAmount = total;
                            model.WithdrawalFee = fee;
                            model.WithdrawalBankName = bankName;
                            model.WithdrawalCardNumber = cardNumber;
                            model.WithdrawalCardName = cardName;
                            model.PaymentStatus = (int)PaymentRecordStatus.未付款;
                            model.PaymentDate = null;
                            model.TransferFee = 0;
                            model.NoticeStatus = (int)NoticeStatusStatus.未通知;
                            model.NoticeLastTime = null;
                            model.NoticeTimes = 0;
                            //model.ReqeustBody = 0;
                            //model.NoticeFail = 0;
                            //model.Remark = 0;
                            model.ProxyMerchantId = 0;
                            model.CreatedBy = UserId;
                            model.CreatedDate = DateTime.Now;
                            paymentRecords.Add(model);
                        }
                        #endregion

                        var sum = paymentRecords.Sum(c => c.WithdrawalAmount);

                        if(merchant.PaymentBalance< sum)
                        {
                            throw new Exception($"余额不足 代付余额:{merchant.PaymentBalance},订单总金额:{sum}");
                        }


                    }
                }
            }
            catch(Exception ex)
            {
                response.Message = ex.Message;
            }
            

            return Json(response);
        }
        #endregion

        #region 用户管理
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Users()
        {
            return View("User");
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserResponse></returns>
        public IActionResult UserQuery(UserQuery query)
        {
            query.UserId = UserId;
            var list = _authService.GetUserPager(query);

            return PartialView("_UserQuery", list);
        }

        /// <summary>
        /// 备注
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult ConfirmPassWord(int id)
        {

            var model = _authService.GetUser(UserId);

            return View("ConfirmPassWord",model);
        }
        
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ResetPassWord(ResetPassWordRequest request)
        {
            request.Id = UserId;

            var response = _authService.TwoResetPassWord(request);

            return Json(response);
        }

        /// <summary>
        /// 备注
        /// </summary>
        /// <returns>视图</returns>
        public IActionResult GoogleVerify()
        {
            var user = _authService.GetUser(UserId);

            var secretKey = Guid.NewGuid().ToString("N").ToLower();
            
            var setupCode = new TwoFactorAuthenticator().GenerateSetupCode("911pay", user.Account, secretKey, 300, 300);
            ViewBag.qrCodeImageUrl = setupCode.QrCodeSetupImageUrl;
            ViewBag.secretKey = secretKey;
            return View("GoogleVerify");
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GoogleVerify(string secretKey)
        {
            var response = new JResult()
            {
                Success = false
            };

            response = _authService.MerchantGoogleVerify(UserId, (int)GoogleVerifyStatus.启用, secretKey);

            return Json(response);
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GoogleVerifyStatu()
        {
            var response = new JResult()
            {
                Success = false
            };

            response = _authService.GoogleVerify(UserId, (int)GoogleVerifyStatus.禁用);

            return Json(response);
        }
        
        #endregion
    }
}
